import { Hono } from "hono";
import { z } from "zod";
import validator from "../middlewares/validate";
import { AuthService } from "../services/auth";
import Responder from "../middlewares/response";
import { authMiddleware } from "../middlewares/auth";

const auth = new Hono();
const authService = new AuthService();

const registerSchema = z.object({
  email: z.string().email(),
  password: z.string().min(6),
  username: z.string().min(2),
  gender: z.string().optional(),
  description: z.string().optional(),
  birthdayAt: z.string().optional(),
});

const loginSchema = z.object({
  email: z.string().email(),
  password: z.string(),
});

const updateUserSchema = z.object({
  username: z.string().min(2).optional(),
  gender: z.string().optional(),
  description: z.string().optional(),
  birthdayAt: z.string().optional(),
});

// 注册
auth.post("/register", validator("json", registerSchema), async (c) => {
  const data = c.req.valid("json");
  const result = await authService.register({
    ...data,
    birthdayAt: data.birthdayAt ? new Date(data.birthdayAt) : undefined,
  });
  
  // 确保返回的数据结构与 AuthResponse 一致
  return Responder.success("注册成功").setData({
    token: result.token,
    user: {
      _id: result.user._id,
      email: result.user.email,
      username: result.user.username,
      gender: result.user.gender,
      description: result.user.description,
      birthdayAt: result.user.birthdayAt,
      createdAt: result.user.createdAt
    }
  }).build(c);
});

// 登录
auth.post("/login", validator("json", loginSchema), async (c) => {
  const data = c.req.valid("json");
  const result = await authService.login(data);
  return Responder.success("登录成功").setData(result).build(c);
});

// 登出
auth.post("/logout", async (c) => {
  await authService.logout(c);
  return Responder.success("登出成功").build(c);
});

// 获取用户信息
auth.get("/me", authMiddleware, async (c) => {
  const userId = c.get("userId");
  const result = await authService.getUserById(userId);
  if (!result) {
    return Responder.fail("获取用户信息失败").build(c);
  }
  return Responder.success().setData(result).build(c);
});

// 更新用户信息
auth.put("/me", authMiddleware, validator("json", updateUserSchema), async (c) => {
  const userId = c.get("userId");
  const data = c.req.valid("json");
  const result = await authService.updateUser(userId, {
    ...data,
    birthdayAt: data.birthdayAt ? new Date(data.birthdayAt) : undefined,
  });
  
  if (!result) {
    return Responder.fail("更新用户信息失败").build(c);
  }
  
  return Responder.success("用户信息更新成功").setData(result).build(c);
});

// 删除用户
auth.delete("/me", authMiddleware, async (c) => {
  const userId = c.get("userId");
  await authService.deleteUser(userId);
  return Responder.success("用户删除成功").build(c);
});

export default auth;
